package com.cskaoyan.service;
/*
 * @author 魏骏杰
 */


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.bean.mini_program_storage_upload.UploadVo;

import com.cskaoyan.exception.MarketException;
import com.cskaoyan.mapper.StorageMapper;
import com.cskaoyan.utils.ConstantPropertiesUtils;
import com.cskaoyan.utils.FileUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class MiniProgramStorageServiceImpl implements MiniProgramStorageService {
    @Autowired
    StorageMapper storageMapper;

    @Override
    public UploadVo addStorage(MultipartFile file) throws MarketException {
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        Storage storage = new Storage();
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            InputStream inputStream = file.getInputStream();
            String filename = "";

            String originalFilename = file.getOriginalFilename();
            //uuid 添加唯一值，使文件名不重复
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //文件拓展名
            String fileExtensionName = FileUtils.getFileExtensionName(originalFilename);
            filename = uuid + "." + fileExtensionName;
            storage.setKey(filename);

            //根据日期进行分类
            String dataPath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            if ("xls".equals(fileExtensionName) || "xlxs".equals(fileExtensionName)) {
                filename = "Excel/" + dataPath + "/" + filename;
            } else {
                filename = dataPath + "/" + filename;
            }


            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            storage.setUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize(((int) file.getSize()));
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());

        int insertRow = storageMapper.insertSelective(storage);
        if (insertRow <= 0) {
            throw new MarketException("头像上传失败");
        }

        //头像上传成功
        Storage storageInfo = storageMapper.selectByKey(storage.getKey());
        UploadVo storageVo = new UploadVo();
        storageVo.setId(storageInfo.getId());
        storageVo.setKey(storageInfo.getKey());
        storageVo.setName(storageInfo.getName());
        storageVo.setType(storageInfo.getType());
        storageVo.setSize(storageInfo.getSize());
        storageVo.setUrl(storageInfo.getUrl());
        storageVo.setAddTime(storageInfo.getAddTime());
        storageVo.setUpdateTime(storageInfo.getUpdateTime());
        return storageVo;
    }
}
